// Copyright (c) MatrixFramework. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using Matrix.ServiceCommunication.Services;

namespace Matrix.ServiceCommunication.Discovery.LoadBalancing;

/// <summary>
/// 随机负载均衡器
/// </summary>
public class RandomLoadBalancer : ILoadBalancer
{
    private readonly Random _random;

    public string StrategyName => "Random";

    public RandomLoadBalancer()
    {
        _random = new Random();
    }

    public RandomLoadBalancer(int? seed)
    {
        _random = seed.HasValue ? new Random(seed.Value) : new Random();
    }

    public ServiceInstance Select(IList<ServiceInstance> instances)
    {
        if (instances == null || !instances.Any())
        {
            throw new ArgumentException("实例列表不能为空", nameof(instances));
        }

        var healthyInstances = instances.Where(i => i.Healthy && i.Enabled).ToList();
        if (!healthyInstances.Any())
        {
            throw new InvalidOperationException("没有可用的健康实例");
        }

        var index = _random.Next(healthyInstances.Count);
        return healthyInstances[index];
    }
}